package liurong.driver.bite;

import java.nio.ByteBuffer;

import com.sun.org.apache.bcel.internal.generic.NEW;

import javafx.geometry.Side;

public class ByteBufTest {

	public static void main(String[] args) throws Exception {
		String testData = "liurongtestdata";

		ByteBuffer buffer = ByteBuffer.allocate(12 + testData.getBytes().length);
		buffer.putInt(1);
		buffer.putInt(2);
		buffer.putInt(testData.getBytes().length);
		buffer.put(testData.getBytes());
		buffer.flip();
		System.out.println(buffer.position());
		System.out.println(buffer.limit());
		printArr(buffer.array());
		System.out.println(new String(buffer.array()));

		ByteBuffer slice2 = buffer.slice();

		byte[] orignArr = buffer.array();
		int code = buffer.getInt();
		int version = buffer.getInt();
		int contentLength = buffer.getInt();
		int position = buffer.position();
		
		
		slice2.position(12);
		ByteBuffer slice3 = slice2.slice();
		slice3.limit(15);
		System.out.println(slice3.position());
		System.out.println(slice3.limit());
		System.out.println(new String(slice3.array()));

		byte[] strarr = new byte[position];

		System.arraycopy(buffer.array(), buffer.position(), strarr, 0, position);
		printArr(orignArr);
		System.out.println("code=" + code);
		System.out.println("version=" + version);
		System.out.println("contentLenth=" + contentLength);
		printArr(strarr);
		System.out.println("customData=" + new String(strarr));
	}

	public static void printArr(byte[] bytes) {
		for (byte b : bytes) {
			System.out.print(b);
		}
		System.out.println();
	}

	public static int byteArrayToInt(byte[] bytes) {
		int value = 0;
		// 由高位到低位
		for (int i = 0; i < 4; i++) {
			int shift = (4 - 1 - i) * 8;
			value += (bytes[i] & 0x000000FF) << shift;// 往高位游
		}
		return value;
	}

	class Header {

		// 4
		private int code;
		// 4
		private int version;
		// 4
		private int contentLength;

		public Header(int code, int version, int contentLength) {
			super();
			this.code = code;
			this.version = version;
			this.contentLength = contentLength;
		}

		public int getCode() {
			return code;
		}

		public void setCode(int code) {
			this.code = code;
		}

		public int getVersion() {
			return version;
		}

		public void setVersion(int version) {
			this.version = version;
		}

		public int getContentLength() {
			return contentLength;
		}

		public void setContentLength(int contentLength) {
			this.contentLength = contentLength;
		}

	}
}
